/*
 *Author: 蔡亚风
 *Date: 2022-04-29 16:28:42
 *LastEditTime: 2022-04-29 16:28:42
 *LastEditors: 蔡亚风
 *Description:
 *FilePath: \prod\src\utils\index.js
 */
// 视频文件长度、大小校验
export const verifyVideo = (file, maxSize = 15, maxLength = 10) => {
  return new Promise((reslove, reject) => {
    console.log('maxSize==>', maxSize, 'maxLength==>', Number(maxLength))
    // 判断浏览器
    /* let userAgent = navigator.userAgent //取得浏览器的userAgent字符串
    let MicroMessenger = userAgent.indexOf("MicroMessenger") > -1 //判断是否微信内置浏览器
    let isIPhone = userAgent.indexOf("iPhone") > -1 //判断是否是iPhone */
    let fileurl = URL.createObjectURL(file)
    let duration //视频时长
    let n = new FileReader()
    let fileSize = file.size / 1024 / 1024 //获取文件大小 (Mb)
    n.readAsDataURL(file)
    n.onloadend = function () {
      console.log('文件大小(M)' + fileSize)
      if (fileSize) {
        if (fileSize > Number(maxSize)) {
          return reject(`请上传小于${maxSize}MB视频，拍摄时可调低手机拍摄像素`)
        }
      }

      let video = document.createElement('video')
      video.src = fileurl
      video.setAttribute('playsinline', 'true')
      video.setAttribute('autoplay', 'true')
      video.setAttribute('preload', 'auto')
      video.setAttribute('webkit-playsInline', 'true')
      video.setAttribute('x-webkit-airplay', 'allow')
      video.setAttribute('x5-video-player-type', 'h5')
      video.setAttribute('x5-video-player-fullscreen', 'true')
      video.setAttribute('x5-video-orientation', 'landscape|portrait')
      try {
        //  让移动端视频开始缓冲
        if (window.WeixinJSBridge) {
          window.WeixinJSBridge.invoke(
            'getNetworkType',
            {},
            () => {
              video.play()
              video.pause()
            },
            false
          )
        } else {
          video.play()
          video.pause()
        }
      } catch (error) {
        video.play()
        video.pause()
        console.log(error)
      }

      video.onloadedmetadata = function (e) {
        duration = Math.floor(video.duration) //(s)
        console.log('视频时长(s):' + duration)
        console.log(Number(maxLength))
        if (duration > Number(maxLength)) {
          return reject(`视频时间过长，请重新录制。(最长${maxLength}s)`)
        }
        if (duration <= 1) {
          return reject(`视频时间过短，请重新录制。`)
        }
        reslove()
      }
    }
  })
}
